const main = {
    container: document.getElementById( 'container' ),
    button: null,
    // 移动后延迟请求
    MOVE_DIFF_TIMES: 1000,
    // 设置缩放比和标尺的比例
    ZOOM_SCALE: [ '100', '100', '100', '100' ],
    WIDNOW_W: 0,
    WIDNOW_H: 0,

    // 控制每次只能调用一次
    ones: true,
    // 地图
    map: null,
    // 标记
    marker: null,
    // 当前 除自身外其他 店铺点标记集合
    markers: [],

    // 记录上一次执行请求时的中心平面坐标点 {x:1,y:1}
    afterPos: null,
    // 由于点击事件会触发移动  添加一个控制
    isClick: false,

    // 当前位置dom
    me: `<div class="me-icon">
            <div class="dot"></div>
            <div class="pulse"></div>
            <div class="pulse1"></div>
        </div>`,
    shop(src='https://assets.goodsogood.com/static/consumerMap/shop-active.png?x-oss-process=image/quality,Q_100/resize,m_fill,h_80,w_80'){
        return `<div style="width: 30px;height: 30px;overflow: hidden;border-radius: 50%;"><img src="${src}?x-oss-process=image/quality,Q_100/resize,m_fill,h_80,w_80" style="width: 100%;height: 100%;"/></div>`
    },
    shopActive: `<img src="https://assets.goodsogood.com/static/consumerMap/shop.png" style="width: 30px;height: 36px;margin-top: -15px;"/>`,


    init( data ) {
        this.WIDNOW_W = this.container.clientWidth;
        this.WIDNOW_H = this.container.clientHeight;
        // 初始化地图
        this.initMap( data );
    },

    // 初始化地图
    initMap( data ) {
        // 初始化地图
        this.map = new AMap.Map( 'container', {
            resizeEnable: true,
            zoom: 15,
            center: data.pos,
            animateEnable: true,
            rotateEnable: false,
            buildingAnimation: true,
            //features : ['bg','point','road','building'],
            //mapStyle: 'amap://styles/light'
        } );
        // 绑定地图事件
        this.bindMapEvent( this.map );

        // 初始化当前平面坐标
        this.afterPos = this.map.lnglatToPixel( this.map.getCenter() );

        // 初始化当前位置标记
        this.marker = new AMap.Marker( {
            //marker所在的位置
            position: data.pos,
            content: this.me,
            //创建时直接赋予map属性
            map: this.map,
            animation: 'AMAP_ANIMATION_DROP',
        } );

        // 添加一些工具插件
        AMap.plugin( [ 'AMap.ToolBar', 'AMap.Scale', 'AMap.ControlBar', 'AMap.OverView' ],
            () => {
                /* const Tool = new AMap.ToolBar( {
                     locationMarker: this.marker,
                     position: 'LB',
                     locate: true,
                 } );*/
                this.map.addControl( new AMap.Scale() );
                this.map.addControl( new AMap.ControlBar() );
                // this.map.addControl( Tool );
            } );

        // 创建店铺点标记
        this.setNewData( data.list );

        this.marker.setMap( this.map );

        this.button = document.getElementById( 'goToCenter' );
        this.button.style.bottom = '50px';
        this.button.onclick = ()=>{
            this.button.className += ' active';
            console.log(this)
            this.map.setCenter(this.marker.getPosition());
            setTimeout(()=>{
                this.button.className = '';
            },500)
        }
    },
    // 绑定地图的事件
    bindMapEvent( mp ) {

        // 开始评议的时候 收下显示的界面
        mp.on( 'movestart', e => {
            console.log( this.isClick, !this.ones )
            // 如果是点击触发的move则 什么都不做
            if ( this.isClick || !this.ones ) return;

            this.ones = false;

            // 发送数据到rn
            window.postMessage( JSON.stringify( { event: 'MOVE_START' } ) );
            // 复位按钮的位置
            this.setSlefButton( true );

        } );
        // 移动完成地图触发  缩放完成 也会触发
        mp.on( 'moveend', e => {
            this.ones = true;

            if ( this.isClick ) return this.isClick = false;

            // 当记录存在时判断 是否达到请求条件
            if ( this.afterPos ) {
                // 当前位置的平面坐标点
                const currentPos = this.map.lnglatToPixel( this.map.getCenter() ),
                    { x, y } = this.afterPos,
                    difW = this.WIDNOW_W / 2,
                    difH = this.WIDNOW_H / 2;

                if ( !(Math.abs( currentPos.x - x ) >= difW) && !(Math.abs( currentPos.y - y ) >= difH) ) {
                    return
                }
            }

            // 如果是点击触发的move则 什么都不做

            // 清楚之前的定时器
            clearTimeout( this.timer );


            // 拖放完成后允许有1000ms 的延迟
            this.timer = setTimeout( () => {
                // 获取移动后的经纬度
                const { lat, lng } = mp.getCenter();
                //zoom = mp.getZoom();
                // 缩放标尺  米/像素点   结果转换为公里
                let zoomSize = Math.round( mp.getResolution() * this.container.clientWidth ) / 1000;

                // 不做限制 在rn内处理
                /*if ( zoomSize > 100 ) {
                    zoomSize = 100;
                }*/

                // 符合请求后  重置当前中心点的平面坐标
                this.afterPos = this.map.lnglatToPixel( this.map.getCenter() );

                this.getData( lat, lng, zoomSize );
            }, this.MOVE_DIFF_TIMES );

        } );
    },

    // 点击点标记时
    markerClick( e ) {
        // 设置为点击状态
        this.isClick = true;
        this.ones = true;
        const data = e.target.getExtData();

        for ( let i = this.markers.length - 1; i >= 0; i-- ) {
            let _mk = this.markers[ i ],
                _val = _mk.getExtData();

            if ( _mk.getContent() === this.shopActive ) {
                _mk.setContent( this.shop(_val['merchantIcon']) );
                break;
            }
        }

        // 设置当前按钮的位置
        this.setSlefButton();

        // 发送数据到rn
        window.postMessage( JSON.stringify( { event: 'SET_SHOP', data } ) );

        // 移动到当前中心点
        this.map.setCenter( e.target.getPosition() );

        // 设置当前的图标
        e.target.setContent( this.shopActive );
    },

    setNewData( data ) {
        // 先删除之前的标记
        this.map.remove( this.markers );

        data.map( val => {
            // 初始化店铺标记
            var marker = new AMap.Marker( {
                //marker所在的位置
                position: [ val[ 'longitude' ], val[ 'latitude' ], ],
                //icon :'./img/map/shop.png',
                content: this.shop(val['merchantIcon']),
                //创建时直接赋予map属性
                map: this.map,
                animation: 'AMAP_ANIMATION_DROP',
                clickable: true,
                topWhenClick: true,
                extData: val,
            } );
            marker.on( 'click', e => this.markerClick( e ) );

            this.markers.push( marker );
        } );
    },
    getData( curLatitude, curLongitude, radius ) {
        const data = {
            event: 'GET_DATA',
            data: { curLatitude, curLongitude, radius }
        };

        window.postMessage( JSON.stringify( data ) );
    },

    setSlefButton( isReset ) {
        if ( isReset ) {
            this.button.style.bottom = '50px';
        } else {
            this.button.style.bottom = '140px';
        }
    }
};
/*
var _d = '{"pos":[106.562963,29.521171],"list":[{"address":"重庆市江北区邦兴北都19-6（服务热线13101201310）","distanceMeter":"6516","latitude":"29.57270200","longitude":"106.53105200","storeIcon":"http://img.goodsogood.com/file/20170328/B8FA680764CD46F09588BC00C191BE1E.jpeg","storeId":"729617B4C6FC4FA3B8A221CFDEB97F91","storeName":"乐乐达（手机上门维修）","tradeName":"生活服务"},{"address":"重庆市南岸区金紫街112号附7号","distanceMeter":"30","latitude":"29.521022","longitude":"106.562711","storeIcon":"http://img.goodsogood.com/file/20170302/29EB348518EF43D1AEE9ECB3125F682D.jpeg","storeId":"DFFD5F630FDD4786A1EA7991548E1245","storeName":"沁园（泰正花园店）","tradeName":"餐饮美食"},{"address":"南岸区南城大道203号","distanceMeter":"232","latitude":"29.52298500","longitude":"106.56177500","storeIcon":"http://img.goodsogood.com/file/20170314/361C7F18E2974CB38B7BBC7AE071610E.jpeg","storeId":"4B4ACB19853E4FFA8ED37684C435B0AF","storeName":"意念小家（南城大道店）","tradeName":"餐饮美食"},{"address":"南岸区南坪区南城路208号","distanceMeter":"310","latitude":"29.52337200","longitude":"106.56100900","storeIcon":"http://img.goodsogood.com/file/20170307/EB2F4A413B7342BEAE0E3290605143C8.jpeg","storeId":"ACF73CB873CA452AA03A13F34FA43EA4","storeName":"沁园（四小区店）","tradeName":"餐饮美食"},{"address":"南岸区南坪步行街惠工路1-2号","distanceMeter":"418","latitude":"29.524673","longitude":"106.564521","storeIcon":"http://img.goodsogood.com/file/20170308/26B9513666954EF0BF2A883C3EB268A9.jpeg","storeId":"D42167B24E60413CB0FC048589E4F329","storeName":"沁园（惠工店）","tradeName":"餐饮美食"},{"address":"贝迪新城2F[珊瑚中学对面]","distanceMeter":"438","latitude":"29.52474900","longitude":"106.56485000","storeIcon":"http://img.goodsogood.com/file/20171104/F54FC51CEF54422F8587103074C39E7F.jpg","storeId":"8C320C9CF8774A6286A80F1AEE4DCAC4","storeName":"乡村基（贝迪店）","tradeName":"餐饮美食"},{"address":"“重庆城市广场”LG层10号","distanceMeter":"443","latitude":"29.52504800","longitude":"106.56398900","storeIcon":"http://img.goodsogood.com/file/20171025/E0EB89DDD8D646F989ABE8762032D38D.png","storeId":"D1A154BFD0BB4238B87AEB642E2CEC16","storeName":"千叶眼镜（21号店）","tradeName":"购物"},{"address":"重庆市南岸区南湖路15附20号","distanceMeter":"601","latitude":"29.52161700","longitude":"106.56914500","storeIcon":"http://img.goodsogood.com/file/20170105/4E8FDBC106CA4F9B9BA1E49E1B4F76BF.jpeg","storeId":"1A2C05E070BB4017B6A731AFA92B01DB","storeName":"沁园（青青佳苑店）","tradeName":"餐饮美食"},{"address":"汇龙路66号12栋重客隆超市内","distanceMeter":"649","latitude":"29.52031100","longitude":"106.55633300","storeIcon":"http://img.goodsogood.com/file/20171108/1435DC465C5A4130B1634976680DCD52.jpg","storeId":"3CF9D267CC0B427E9DCD5A77C7F392A9","storeName":"沁园（南岸美堤雅城店）","tradeName":"餐饮美食"},{"address":"南坪街道珊瑚路4号附31号","distanceMeter":"740","latitude":"29.52490500","longitude":"106.56928500","storeIcon":"http://img.goodsogood.com/file/20170314/7294311DD999447FA2784214CB3E39A6.jpeg","storeId":"9DA7C19D33A94335A34C7CBC31999F94","storeName":"沁园（南坪万达店）","tradeName":"餐饮美食"}]}';

main.init( JSON.parse( _d ) );*/

// 获取RN发送的数据
document.addEventListener( 'message', e => {
    var data = JSON.parse( e.data );

    switch ( data.event ) {
        case 'INIT':
            main.init( data.data );
            break;
        case 'SET_DATA':
            main.setNewData( data.data );
            break;
    }
} );

